package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.PromptDao;
import com.leoman.entity.Prompt;
import com.leoman.service.PromptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * PromptServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:00.
 */
@Service
public class PromptServiceImpl implements PromptService {

    @Autowired
    private PromptDao promptDao;

    @Override
    public List<Prompt> findAll() {
        return promptDao.findAll();
    }

    @Override
    public Page<Prompt> find(int pageNum, int pageSize) {
        return promptDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Prompt> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Prompt getById(int id) {
        return promptDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        promptDao.delete(id);
    }

    @Override
    public Prompt create(Prompt prompt) {
        return promptDao.save(prompt);
    }

    @Override
    public Prompt update(Prompt prompt) {
        return promptDao.save(prompt);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Integer savePrompt(Integer promptId, Integer type, String content) {
        try {
            Prompt prompt;
            if (null == promptId) {
                prompt = new Prompt();
            } else {
                prompt = promptDao.findOne(promptId);
                prompt.setUpdateTime(System.currentTimeMillis());
            }

            Prompt tempPrompt = promptDao.findOneByType(type);
            if (null != tempPrompt) {
                prompt = tempPrompt;
                prompt.setUpdateTime(System.currentTimeMillis());
            }

            prompt.setType(type);
            prompt.setContent(content);

            promptDao.save(prompt);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}